package com.matang;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.xmlpull.v1.XmlPullParser;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Environment;
import android.os.Handler;
import android.util.Log;
import android.util.Xml;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ImageButton;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.method.CommonMethodSoap;
import com.method.VersionMsg;

public class FirstPage extends Activity {

	RelativeLayout fy_matang;// �����׹�
	RelativeLayout fy_MenberCente;// ��Ա����
	RelativeLayout fy_OrderItem;// ������ѯ
	RelativeLayout fy_yuechaxun;// ���
	RelativeLayout fy_jifenhuangou;// ���
	RelativeLayout fy_saosao;// ɨһɨ
	RelativeLayout fy_dianneishipin;// ���
	RelativeLayout fy_tongxin;// ɨһɨ
	RelativeLayout fy_menberlogin;// ��Ա��¼
	ImageButton callbutton;// 400�绰
	public static final String UPDATE_SERVER = "http://www.ntfymr.com/hairinfo/source/matangyigou/";
	public static final String UPDATE_APKNAME = "MatangYiShopping.apk";
	public static final String UPDATE_VERXML = "Update.xml";
	public String appanme;
	public String apkName;
	public String versionName;
	public int versionCode;
	public int localversionCode;
	public String localversionName;
	public ProgressDialog pressdialog;
	public String TAG = "version";
	Handler handler = new Handler();

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		// requestWindowFeature(Window.FEATURE_NO_TITLE);
		super.onCreate(savedInstanceState);
		// TextView txview = (TextView) findViewById(android.R.id.title);
		// txview.setGravity(Gravity.CENTER);
		setContentView(R.layout.activity_main_m);
		if (CommonMethodSoap.isNetAvaliable(FirstPage.this)) {
			initLoadAsny();
		} else {
			Toast.makeText(this, "��������.........", Toast.LENGTH_SHORT).show();
		}
		initview();
	}

	void initview() {
		fy_matang = (RelativeLayout) findViewById(R.id.relate_matang);
		fy_MenberCente = (RelativeLayout) findViewById(R.id.relate_MenberCenter);
		fy_OrderItem = (RelativeLayout) findViewById(R.id.relate_OrderItem);
		fy_yuechaxun = (RelativeLayout) findViewById(R.id.relate_yuechaxun);
		fy_jifenhuangou = (RelativeLayout) findViewById(R.id.relate_jifenhuangou);
		fy_saosao = (RelativeLayout) findViewById(R.id.relate_saosao);
		callbutton = (ImageButton) findViewById(R.id.callbutton);
		fy_tongxin = (RelativeLayout) findViewById(R.id.relate_tongxin);
		fy_dianneishipin = (RelativeLayout) findViewById(R.id.relate_dianneiship);
		fy_menberlogin = (RelativeLayout) findViewById(R.id.relate_menberlogin);

		fy_matang.setOnClickListener(listener);
		fy_MenberCente.setOnClickListener(listener);
		fy_OrderItem.setOnClickListener(listener);
		fy_yuechaxun.setOnClickListener(listener);
		fy_jifenhuangou.setOnClickListener(listener);
		fy_tongxin.setOnClickListener(listener);
		fy_dianneishipin.setOnClickListener(listener);
		fy_saosao.setOnClickListener(listener);
		callbutton.setOnClickListener(listener);
		fy_menberlogin.setOnClickListener(listener);
	}

	private OnClickListener listener = new OnClickListener() {

		@Override
		public void onClick(View v) {
			// TODO Auto-generated method stub
			Intent intent = new Intent(FirstPage.this, MainActivity.class);
			switch (v.getId()) {
			case R.id.relate_matang:
				intent.putExtra("tag", "fy_matang");
				startActivity(intent);
				break;
			// ��Ա����
			case R.id.relate_MenberCenter:
				intent.putExtra("tag", "fy_MenberCenter");
				startActivity(intent);
				break;
			// ��������
			case R.id.relate_OrderItem:
				intent.putExtra("tag", "fy_OrderItem");
				startActivity(intent);
				break;
			// ����ѯ
			case R.id.relate_yuechaxun:
				intent.putExtra("tag", "fy_yuechaxun");
				startActivity(intent);
				break;
			// ��ֻ���
			case R.id.relate_jifenhuangou:
				intent.putExtra("tag", "fy_jifenhuangou");

				startActivity(intent);
				break;
			// ɨһɨ
			case R.id.relate_saosao:
//				intent.putExtra("tag", "fy_saosao");
//				startActivity(intent);
				Toast.makeText(FirstPage.this, "�����з���", Toast.LENGTH_SHORT).show();
				break;
			case R.id.callbutton:
				Intent call = new Intent();
				call.setAction(Intent.ACTION_CALL);
				call.setData(Uri.parse("tel:400-600-8733"));
				startActivity(call);
				break;

			case R.id.relate_menberlogin:
				intent.putExtra("tag", "fy_menberlogin");
				startActivity(intent);
				break;
			case R.id.relate_dianneiship:
				Toast.makeText(FirstPage.this, "�����з���", Toast.LENGTH_SHORT).show();
				break;
			case R.id.relate_tongxin:
				Toast.makeText(FirstPage.this, "�����з���", Toast.LENGTH_SHORT).show();
				break;
			default:
				break;
			}
		}
	};

	void initLoadAsny() {
		// �첽���ض�ȡftp����xml����ݵİ汾��
		LoadAnsyReadVersionXML versionxml = new LoadAnsyReadVersionXML();
		versionxml.execute();
	}

	class LoadAnsyReadVersionXML extends AsyncTask<Void, Void, Void> {

		@Override
		protected void onPostExecute(Void result) {
			// TODO Auto-generated method stub
			// ���а汾�ŵıȽ�
			bijiaoVersion();
			super.onPostExecute(result);
		}

		@Override
		protected Void doInBackground(Void... params) {
			// TODO Auto-generated method stub
			// ����url�����Ӳ����н���xml���
			try {
				URL url = new URL(UPDATE_SERVER + UPDATE_VERXML + "?dt="
						+ System.currentTimeMillis());
				URLConnection connection = (URLConnection) url.openConnection();
				connection.connect();
				InputStream inputstream = connection.getInputStream();
				XmlPullParser xml = Xml.newPullParser();
				xml.setInput(inputstream, "utf-8");
				int event = xml.getEventType();
				while (event != XmlPullParser.END_DOCUMENT) {
					switch (event) {
					case XmlPullParser.START_TAG:
						if ("appname".equals(xml.getName())) {
							appanme = xml.nextText();
							Log.i("appanme", "---appanme:" + appanme);
						}
						if ("apkName".equals(xml.getName())) {
							apkName = xml.nextText();
							Log.i("apkName", "---apkName:" + apkName);
						}
						if ("versionName".equals(xml.getName())) {
							versionName = xml.nextText();
							Log.i("version", "---versionName:" + versionName);
						}
						if ("versionCode".equals(xml.getName())) {
							versionCode = Integer.parseInt(xml.nextText());
							Log.i("version", "---versionCode:" + versionCode);
						}
						break;

					default:
						break;
					}
					event = xml.next();
				}
			} catch (Exception e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return null;
		}

	}

	public void bijiaoVersion() {

		localversionCode = VersionMsg.getVersionCode(this);
		localversionName = VersionMsg.getVersionName(this);
		// Toast.makeText(FirstPage.this,
		// "local:" + localversionCode + ",ftp:" + versionCode,
		// Toast.LENGTH_LONG).show();
		if (localversionCode < versionCode) {
			// ��code��name����������������ʱ������и���
			downNewVersionUpdate();
		} else {
			// notNewVersionShow();
		}

	}

	void downNewVersionUpdate() {
		StringBuffer buffer = new StringBuffer();
		buffer.append("��ǰ�汾��");
		buffer.append(localversionName);
		buffer.append(",versioncode");
		buffer.append(localversionCode);
		buffer.append(",�����°汾:");
		buffer.append(versionName);
		buffer.append("code");
		buffer.append(versionCode);
		Dialog dialog = new AlertDialog.Builder(this)
				.setTitle("�������")
				.setMessage((buffer).toString())
				.setPositiveButton("����", new DialogInterface.OnClickListener() {

					@Override
					public void onClick(DialogInterface dialog, int which) {
						// TODO Auto-generated method stub

						pressdialog = new ProgressDialog(FirstPage.this);
						pressdialog.setTitle("��������");
						pressdialog.setMessage("���Ժ�...");
						pressdialog.setProgressStyle(pressdialog.STYLE_SPINNER);
						Log.i("version", UPDATE_SERVER + UPDATE_APKNAME
								+ "?dt=" + System.currentTimeMillis());
						downFile(UPDATE_SERVER + UPDATE_APKNAME + "?dt="
								+ System.currentTimeMillis());

					}
				})
				.setNegativeButton("ȡ�����",
						new DialogInterface.OnClickListener() {

							@Override
							public void onClick(DialogInterface dialog,
									int which) {
								// TODO Auto-generated method stub

							}
						}).create();
		dialog.show();

	}

	protected void downFile(final String url) {
		pressdialog.show();
		new Thread() {
			public void run() {
				HttpClient client = new DefaultHttpClient();
				HttpGet get = new HttpGet(url);
				Log.i(TAG, "downFile:" + url);
				HttpResponse response;
				try {
					response = client.execute(get);
					HttpEntity entity = response.getEntity();
					long length = entity.getContentLength();
					InputStream is = entity.getContent();
					FileOutputStream fileOutputStream = null;
					if (is != null) {

						File file = new File(
								Environment.getExternalStorageDirectory(),
								UPDATE_APKNAME);
						Log.i(TAG, "Environment.getExternalStorageDirectory()"
								+ Environment.getExternalStorageDirectory());
						fileOutputStream = new FileOutputStream(file);
						byte[] buf = new byte[1024];
						int ch = -1;
						int count = 0;
						while ((ch = is.read(buf)) != -1) {
							fileOutputStream.write(buf, 0, ch);
							count += ch;
							if (length > 0) {
							}
						}
					}
					fileOutputStream.flush();
					if (fileOutputStream != null) {
						fileOutputStream.close();
					}
					Log.i(TAG, "-----------------�������--------------");

					// �Զ���װ
					down();
				} catch (ClientProtocolException e) {
					Log.i(TAG, "ClientProtocolException" + e.getMessage());
				} catch (IOException e) {
					Log.i(TAG, "IOException" + e.getMessage());
				}
			}

		}.start();

	}

	void down() {

		handler.post(new Runnable() {

			@Override
			public void run() {
				// TODO Auto-generated method stub
				pressdialog.cancel();
				update();

			}
		});

	}

	void update() {
		Intent intent = new Intent(Intent.ACTION_VIEW);
		intent.setDataAndType(Uri.fromFile(new File(Environment
				.getExternalStorageDirectory(), UPDATE_APKNAME)),
				"application/vnd.android.package-archive");
		startActivity(intent);

	}
}
